package com.zsp.comic.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zsp.comic.entity.Comic;
import com.zsp.comic.entity.JsonResult;
import com.zsp.comic.entity.ResultCode;
import com.zsp.comic.service.ComicService;
import com.zsp.comic.util.ResultTool;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.websocket.server.PathParam;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author gan
 * @create 2020-12-08 10:23
 */
@RestController
@RequestMapping("/comic")
public class ComicController {

    @Resource
    private ComicService comicService;

    //判断所查单个数据是否为空
    private JsonResult hasOneData(Comic comic){
        if (comic == null){
            return ResultTool.fail(ResultCode.COMMON_FAIL);
        }else {
            return ResultTool.success(comic);
        }
    }

    //判断所查多个数据的集合是否为空
    private JsonResult hasManyData(List<Comic> comics){
        if (comics == null){
            return ResultTool.fail(ResultCode.COMMON_FAIL);
        }else {
            return ResultTool.success(comics);
        }
    }

    //判断所查多个数据的分页对象是否为空
    private JsonResult hasManyData(PageInfo<Comic> pageInfo){
        if (pageInfo == null){
            return ResultTool.fail(ResultCode.COMMON_FAIL);
        }else {
            return ResultTool.success(pageInfo);
        }
    }

    @GetMapping("/getAllComic/{page}/{size}")
    public JsonResult getAllComic(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageHelper.startPage(page,size);
        List<Comic> comics = comicService.getAllComic();

        PageInfo<Comic> pageInfo = new PageInfo<>(comics);

        return hasManyData(pageInfo);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_customer', 'ROLE_admin')")
    @GetMapping("/getComicByUserId/{userId}")
    public JsonResult getComicByUserId(@PathVariable Integer userId){
        List<Comic> comics = comicService.getComicByUserId(userId);
        return hasManyData(comics);
    }

    @GetMapping("/getAllCondition")
    public JsonResult getAllCondition(){
        return ResultTool.success(comicService.getAllCondition());
    }


    @GetMapping("/getComicById/{id}")
    public JsonResult getComicById(@PathVariable Integer id){
        Comic comic = comicService.getComicById(id);
        return hasOneData(comic);
    }

    @PostMapping("/getComicByName/{page}/{size}")
    public JsonResult getComicByName(@PathVariable("page") Integer page, @PathVariable("size") Integer size, @RequestBody Comic comic){
        PageHelper.startPage(page,size);

        List<Comic> comics = comicService.getComicByName(comic.getName());

        PageInfo<Comic> pageInfo = new PageInfo<>(comics);

        return hasManyData(pageInfo);
    }

    //按条件查询动漫（不传入条件则查询所有动漫）
    @PostMapping("/getComicByCondition/{page}/{size}")                                                              //用Comic实体来接收前台传过来的条件参数对象
    public JsonResult getComicByCondition(@PathVariable("page") Integer page, @PathVariable("size") Integer size,@RequestBody Comic condition){
        PageHelper.startPage(page,size);

        List<Comic> searchComics = comicService.getComicByCondition(condition);
        PageInfo<Comic> pageInfo = new PageInfo<>(searchComics);
        return hasManyData(pageInfo);
    }

    //每日更新页的动漫，连载动漫
    @GetMapping("/getSerialComic/{page}/{size}")
    public JsonResult getSerialComic(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageHelper.startPage(page,size);
        List<Comic> comics = comicService.serialComic();

        PageInfo<Comic> pageInfo = new PageInfo<>(comics);

        return hasManyData(pageInfo);
    }

    //首页更新页的动漫，连载动漫
    @GetMapping("/getIndexSerialComic/{num}")
    public JsonResult getIndexSerialComic(@PathVariable("num") Integer num){

        List<Comic> comics = comicService.indexSerialComic(num);

        return hasManyData(comics);
    }

    //推荐页的动漫，推荐动漫
    @GetMapping("/getRecommendComic/{page}/{size}")
    public JsonResult getRecommendComic(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageHelper.startPage(page,size);
        List<Comic> comics = comicService.recommendComic();

        PageInfo<Comic> pageInfo = new PageInfo<>(comics);

        return hasManyData(pageInfo);
    }

    //首页推荐页的动漫，推荐动漫
    @GetMapping("/getIndexRecommendComic/{num}")
    public JsonResult getIndexRecommendComic(@PathVariable("num") Integer num){
        List<Comic> comics = comicService.indexRecommendComic(num);

        return hasManyData(comics);
    }

    @PreAuthorize("hasAuthority('ROLE_admin')")
    @GetMapping("/getAllComicWithAdminAuthority/{page}/{size}")
    public JsonResult getAllComicWithAdminAuthority(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageHelper.startPage(page,size);
        List<Comic> comics = comicService.getAllComicWithAdminAuthority();

        PageInfo<Comic> pageInfo = new PageInfo<>(comics);

        return hasManyData(pageInfo);
    }

    @PreAuthorize("hasAuthority('ROLE_admin')")
    @GetMapping("/getComicByIdWithAdminAuthority/{id}")
    public JsonResult getComicByIdWithAdminAuthority(@PathVariable Integer id){
        Comic comic = comicService.getComicByIdWithAdminAuthority(id);
        return hasOneData(comic);
    }

    @PreAuthorize("hasAuthority('ROLE_admin')")
    @PostMapping("/getComicByNameWithAdminAuthority/{page}/{size}")
    public JsonResult getComicByNameWithAdminAuthority(@PathVariable("page") Integer page, @PathVariable("size") Integer size, @RequestBody Comic comic){
        PageHelper.startPage(page,size);

        List<Comic> comics = comicService.getComicByNameWithAdminAuthority(comic.getName());

        PageInfo<Comic> pageInfo = new PageInfo<>(comics);

        return hasManyData(pageInfo);

    }


    @PreAuthorize("hasAuthority('ROLE_admin')")
    @PostMapping("/test")
    public JsonResult test(){
        System.out.println("test执行了");
        return ResultTool.success("test执行了");
    }

    @PreAuthorize("hasAuthority('ROLE_admin')")
    @PostMapping("/addComic")
    public JsonResult addComic(@RequestBody Comic comic){
        if (null != comic){
            boolean isAddSuccess = comicService.addComic(comic);
            return ResultTool.success(isAddSuccess);
        }
        return ResultTool.fail();
    }

    @PreAuthorize("hasAuthority('ROLE_admin')")
    @PostMapping("/updateComic")
    public JsonResult updateComic(@RequestBody Comic comic){
//        System.out.println(comic.getVideoMap());
//        System.out.println(comic.getMagnetMap());
        if (null != comic){
            boolean isUpdateSuccess = comicService.updateComic(comic);
            return ResultTool.success(isUpdateSuccess);
        }
        return ResultTool.fail();
    }

    @PreAuthorize("hasAuthority('ROLE_admin')")
    @PostMapping("/deleteComic")
    public JsonResult deleteComic(@RequestParam Integer comicId){
        return ResultTool.success(comicService.deleteComic(comicId));
    }

    /*@RequestMapping("/fileUpload")
    public JsonResult fileUpload(@RequestParam("file") MultipartFile upload) {
        System.out.println("接收到了");
        if (upload.isEmpty()) {
            System.out.println("文件为空");
        }
        String path = "E:\\file\\vue\\images";
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }

        //获取上传文件的后缀名
        String fileType  =upload.getOriginalFilename().substring(upload.getOriginalFilename().indexOf("."));
        // 获取上传文件的名称
        //String filename = upload.getOriginalFilename();
        // 把文件的名称设置唯一值，uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String filename = uuid + fileType;

        try {
            upload.transferTo(new File(path, filename));
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, Object> result = new HashMap();
        result.put("message","上传成功");
        result.put("filename", filename);

        return ResultTool.success(result);
    }*/
}
